package cn.otrue.patienthealthmanager.fragment;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.Toast;
import cn.otrue.patienthealthmanager.R;
import cn.otrue.patienthealthmanager.activity.DoctorJianKang;
import cn.otrue.patienthealthmanager.activity.LoginActivity;
import cn.otrue.patienthealthmanager.activity.MainDataInfoActivity;
import cn.otrue.patienthealthmanager.activity.TiaoJiaBingliActivity;
import cn.otrue.patienthealthmanager.adapter.MainInfoAdapter;
import cn.otrue.patienthealthmanager.adapter.OfMainInfoAdapter;
import cn.otrue.patienthealthmanager.bean.TransferParameter;
import cn.otrue.patienthealthmanager.http.HttpCons;
import cn.otrue.patienthealthmanager.http.HttpServer;
import cn.otrue.patienthealthmanager.http.ServerHandler;
import cn.otrue.patienthealthmanager.utils.DialogUtil;
import cn.otrue.patienthealthmanager.utils.MyConst;
import cn.otrue.patienthealthmanager.view.SwitchButtonListClickListener;
import cn.otrue.patienthealthmanager.view.SwitchListButton;
import cn.otrue.patienthealthmanager.view.XListView;
import cn.otrue.patienthealthmanager.view.XListView.IXListViewListener;

import com.google.gson.reflect.TypeToken;

/**
 * 首页->资料信息
 * 
 * @author G
 * 
 */
public class MainDataInfoFragment extends BaseFragment implements
		IXListViewListener, OnTouchListener {

	private TextView tv_main_info_tab_left;
	private TextView tv_main_info_tab_right;
	private XListView lv_main_info;
	private List<Map<String, String>> butt = new ArrayList<Map<String, String>>();
	private MainInfoAdapter adapter;
	private int currentPage = 1;
	private List<Map<String, String>> buyy = new ArrayList<Map<String, String>>();
	private int type = 1;
	private AlertDialog alertDialog;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		rootView = inflater.inflate(R.layout.fragment_main_info, container,
				false);
		initView(rootView);

		return rootView;
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		lv_main_info.setPullLoadEnable(false);
		super.onResume();
		if (type == 1) {
			if (!TextUtils.isEmpty(MyConst.getACCOUNT())) {
				butt.clear();
				buyy.clear();
				getpinggu(currentPage);
			}

		} else {

			if (!TextUtils.isEmpty(MyConst.getACCOUNT())) {
				butt.clear();
				buyy.clear();
				getlishi(currentPage);
			}
		}

	}

	private void initView(View rootView) {

		slb_all_doctor = (SwitchListButton) rootView
				.findViewById(R.id.slb_all_doctor);
		// 设置显示的文字
		String[] arr = { "健康评估", "历史资料" };
		// 设置每个textView的宽高
		// 初始化 （数据,宽,高,padding集合(默认为null),点击监听）
		slb_all_doctor.initButton(Arrays.asList(arr), 65, 35, null,
				new SwitchButtonListClickListener() {

					@Override
					public void onGetClicked(int cid) {
						Log.e("Switch", cid + "");
						butt.clear();
						buyy.clear();
						type = cid + 1;
						currentPage = 0;
						if (type == 1) {
							currentPage = 1;
							butt.clear();
							buyy.clear();
							tv_title_other.setVisibility(View.GONE);
							getpinggu(currentPage);
						} else {
							tv_title_other.setVisibility(View.VISIBLE);
							butt.clear();
							buyy.clear();
							getlishi(currentPage);
						}

					}
				});
		// 设置初始的显示的数值
		slb_all_doctor.setClicked(0);

		lv_main_info = (XListView) rootView.findViewById(R.id.lv_main_info);
		lv_main_info.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				if (type == 1) {
					Intent intent = new Intent(getActivity(),
							DoctorJianKang.class);
					intent.putExtra("seq", buyy.get(position - 1).get("seq"));
					startActivity(intent);
				} else {
					Intent intent = new Intent(getActivity(),
							MainDataInfoActivity.class);

					intent.putExtra("seq", butt.get(position - 1).get("seq"));
					startActivity(intent);
				}

			}

		});
		lv_main_info.setPullLoadEnable(false); // 是否开启上拉加载
		lv_main_info.setXListViewListener(this);// 上啦加载和下拉刷新的监听

		adapter = new MainInfoAdapter(rootView.getContext(), butt);
		lv_main_info.setAdapter(adapter);

		tv_title_other = (TextView) getActivity().findViewById(
				R.id.tv_title_othuu);
		if (!TextUtils.isEmpty(MyConst.getACCOUNT())) {
			getpinggu(currentPage);
		}

	}

	private Handler lishiHandler = new ServerHandler() {
		private MainInfoAdapter postAdapter;

		@Override
		public void onSuccess(Bundle data, String state, String msg) {
			onLoad();

			if (state.equals("001")) {

				String tuu = data.getString(HttpCons.DATA);
				Log.e("LLLLL", tuu);
				List<Map<String, String>> iiii = HttpServer.gson.fromJson(tuu,
						new TypeToken<List<Map<String, String>>>() {
						}.getType());
				int iii = butt.size();

				butt.addAll(iiii);
				if (butt.size() > 5) {
					lv_main_info.setPullLoadEnable(true);
				}
				postAdapter = new MainInfoAdapter(rootView.getContext(), butt);
				lv_main_info.setAdapter(postAdapter);
				lv_main_info.setSelection(iii);
				Toast.makeText(rootView.getContext(), "操作成功", 0).show();
			} else {
				Toast.makeText(rootView.getContext(), msg, 0).show();

			}
		}

		@Override
		public void onFail(Bundle data, String state) {
			onLoad();
			if (state.equals(HttpCons.STATE_EXCEPTION)) {
				// 代表进入状态STATE_EXCEPTION 网络异常

				Toast.makeText(rootView.getContext(), "网络异常,请稍后重试",
						Toast.LENGTH_SHORT).show();

			} else if (state.equals(HttpCons.STATE_FORMAT_ERROR)) {
				// 代表进入STATE_FORMAT_ERROR(不是Json)
			} else {
				// 代表进入STATE_ANALYTICAL_ERROR(Json解析错误)

			}
		}
	};

	private Handler jiankangHandler = new ServerHandler() {
		private OfMainInfoAdapter postAdapter;

		@Override
		public void onSuccess(Bundle data, String state, String msg) {
			if (state.equals("001")) {

				String tuu = data.getString(HttpCons.DATA);
				Log.e("LLLLL", tuu);
				List<Map<String, String>> iiii = HttpServer.gson.fromJson(tuu,
						new TypeToken<List<Map<String, String>>>() {
						}.getType());
				int yy = buyy.size();

				buyy.addAll(iiii);
				if (buyy.size() > 5) {
					lv_main_info.setPullLoadEnable(true);
				}
				postAdapter = new OfMainInfoAdapter(rootView.getContext(), buyy);

				lv_main_info.setAdapter(postAdapter);
				lv_main_info.setSelection(yy);
				onLoad();
				Toast.makeText(rootView.getContext(), "操作成功", 0).show();
			} else {
				Toast.makeText(rootView.getContext(), msg, 0).show();
				onLoad();

			}
		}

		@Override
		public void onFail(Bundle data, String state) {

			if (state.equals(HttpCons.STATE_EXCEPTION)) {
				// 代表进入状态STATE_EXCEPTION 网络异常
				onLoad();
				Toast.makeText(rootView.getContext(), "网络异常,请稍后重试",
						Toast.LENGTH_SHORT).show();

			} else if (state.equals(HttpCons.STATE_FORMAT_ERROR)) {
				// 代表进入STATE_FORMAT_ERROR(不是Json)
			} else {
				// 代表进入STATE_ANALYTICAL_ERROR(Json解析错误)

			}
		}
	};

	private View rootView;
	private TextView tv_title_other;
	private SwitchListButton slb_all_doctor;

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {

		// case R.id.tv_main_info_tab_left:
		// type = 1;
		// butt.clear();
		// buyy.clear();
		// getpinggu(currentPage);
		// tv_main_info_tab_left
		// .setBackgroundResource(R.color.switch_butto_open);
		// tv_main_info_tab_right
		// .setBackgroundResource(R.color.switch_butto_off);
		// tv_main_info_tab_left.setTextColor(Color.WHITE);
		// tv_main_info_tab_right.setTextColor(Color.BLACK);
		// if (tv_title_other != null) {
		// tv_title_other.setVisibility(View.GONE);
		// }
		// break;
		// case R.id.tv_main_info_tab_right:
		// type = 2;
		// butt.clear();
		// buyy.clear();
		// getlishi(currentPage);
		// // getpinggu();
		// tv_title_other.setVisibility(View.VISIBLE);
		//
		// tv_title_other.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		// tv_title_other.setVisibility(View.GONE);
		//
		// if (MyConst.getACCOUNT().equals("")) {
		// View dialogView = initDataInputDialog(
		// new DataDialogListener(), 0);
		// if (null != dialogView)
		// alertDialog = DialogUtil.showDialog(
		// MainDataInfoFragment.this.getActivity(),
		// dialogView, true);
		// } else {
		// Intent intent = new Intent(getActivity(),
		// TiaoJiaBingliActivity.class);
		// startActivity(intent);
		//
		// }
		//
		// }
		// });
		//
		// tv_main_info_tab_right
		// .setBackgroundResource(R.color.switch_butto_open);
		// tv_main_info_tab_left
		// .setBackgroundResource(R.color.switch_butto_off);
		// tv_main_info_tab_right.setTextColor(Color.WHITE);
		// tv_main_info_tab_left.setTextColor(Color.BLACK);
		// break;

		default:
			break;
		}
	}

	private View initDataInputDialog(DataDialogListener dataListener, int i) {
		LayoutInflater inflater = LayoutInflater.from(rootView.getContext());
		View view = inflater.inflate(R.layout.dialog_input_daaa, null);
		TextView tv_catt_dialogLeft = (TextView) view
				.findViewById(R.id.tv_catt_dialogLeft);
		tv_catt_dialogLeft.setOnClickListener(dataListener);
		TextView tv_catt_dialogRight = (TextView) view
				.findViewById(R.id.tv_catt_dialogRight);
		tv_catt_dialogRight.setOnClickListener(dataListener);
		return view;

	}

	public class DataDialogListener implements OnClickListener {

		@Override
		public void onClick(View v) {

			switch (v.getId()) {
			case R.id.tv_catt_dialogLeft:// 取消
				alertDialog.dismiss();
				break;
			case R.id.tv_catt_dialogRight:// 确定

				Intent personinfoIntent = new Intent(getActivity(),
						LoginActivity.class);
				startActivity(personinfoIntent);
				alertDialog.dismiss();
			}
		}

	}

	/**
	 * 评估
	 * 
	 * @param i
	 * @param us
	 */
	private void getpinggu(int i) {
		// TODO Auto-generated method stub
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("p_account", MyConst.getACCOUNT());
		TransferParameter parameter = new TransferParameter();
		parameter.setUsername(MyConst.getACCOUNT());
		parameter.setPassword(" ");
		parameter.setCurrentPage(i + "");
		parameter.setPagesize("20");
		parameter.setData(map);
		new HttpServer().post(HttpCons.queryHealthAssessmentReportByPage,
				parameter, jiankangHandler);
	}


	/**
	 * 病例
	 * 
	 * @param i
	 */
	private void getlishi(int i) {
		// TODO Auto-generated method stub
		HashMap<String, Object> map = new HashMap<String, Object>();

		TransferParameter parameter = new TransferParameter();
		parameter.setUsername(MyConst.getACCOUNT());
		parameter.setPassword(" ");
		parameter.setCurrentPage(i + "");
		parameter.setPagesize("20");
		parameter.setData(map);
		new HttpServer().post(HttpCons.QueryHistoricalDataList, parameter,
				lishiHandler);
	}

	private void onLoad() {
		lv_main_info.stopRefresh();
		lv_main_info.stopLoadMore();
		lv_main_info.setRefreshTime("刚刚");
	}

	@Override
	public boolean onTouch(View arg0, MotionEvent arg1) {
		// TODO Auto-generated method stub
		return false;
	}

	public static Fragment newInstance() {
		return new MainDataInfoFragment();
	}

	@Override
	public String setPageName() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onRefresh() {
		currentPage = 1;
		butt.clear();
		buyy.clear();
		if (type == 1) {
			getpinggu(currentPage);
		} else {
			getlishi(currentPage);
		}

	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub

		currentPage++;
		if (type == 1) {
			getpinggu(currentPage);
		} else {
			getlishi(currentPage);
		}

	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		if (isVisibleToUser) {
			if (tv_title_other != null) {
				if (type != 1) {
					tv_title_other.setVisibility(View.VISIBLE);
				}

				tv_title_other.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub

						if (MyConst.getACCOUNT().equals("")) {
							View dialogView = initDataInputDialog(
									new DataDialogListener(), 0);
							if (null != dialogView)
								alertDialog = DialogUtil.showDialog(
										MainDataInfoFragment.this.getActivity(),
										dialogView, true);
						} else {
							Intent intent = new Intent(getActivity(),
									TiaoJiaBingliActivity.class);
							startActivity(intent);

						}

					}
				});
			}
		} else {
			// 相当于Fragment的onPause
			if (tv_title_other != null) {
				tv_title_other.setVisibility(View.GONE);
			}
		}
	}

}
